package com.zhu.websocketdemo.service.impl;

import com.zhu.websocketdemo.dto.RankItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MessageRankService {
    private static final String MESSAGE_RANK_KEY = "chat:message_rank";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 增加用户消息计数
    public void incrementMessageCount(String userId) {
        redisTemplate.opsForZSet().incrementScore(MESSAGE_RANK_KEY, userId, 1);
    }

    // 获取Top10用户
    public List<RankItem> getTopUsers() {
        Set<ZSetOperations.TypedTuple<String>> tuples =  redisTemplate.opsForZSet().reverseRangeWithScores(MESSAGE_RANK_KEY, 0, 9);
        return tuples.stream()
                .map(tuple -> new RankItem(tuple.getValue(), tuple.getScore().intValue())).collect(Collectors.toList());
    }
}
